package com.margo.project.limit.action;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.margo.project.limit.handle.LeakeyBucketLimiter;


@RestController
public class LeakyBucketLimitController {
	
	@Autowired
	private LeakeyBucketLimiter leakeyBucketLimiter;

	/**
	 * localhost:8080/redis/limit/request
	 * @return
	 */
	@RequestMapping(path="/limit/leakey/request")
	private String leakey() {
		String result=null;
		if(leakeyBucketLimiter.acquire()==1) {
			result="fail with limit";
		}else {
			result="success";
		}
		return result;
	}
	
	public static void main(String[] args) throws InterruptedException {
		LeakeyBucketLimiter limiter=new LeakeyBucketLimiter();
		ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(8);
		CountDownLatch latch=new CountDownLatch(30);
		for(int i=0;i<30;i++) {
			newFixedThreadPool.submit(new Runnable() {
				
				@Override
				public void run() {
					latch.countDown();
					int i=limiter.acquire();
					System.out.println("返回结果："+i);
				}
			});
		}
		latch.await();
		System.out.println("休息一下。。。。。。。。。。。。。。");
		Thread.sleep(1000);
		for(int i=0;i<30;i++) {
			newFixedThreadPool.submit(new Runnable() {
				
				@Override
				public void run() {
					int i=limiter.acquire();
					System.out.println("返回结果："+i);
				}
			});
		}
	}
}
